<template>
  <div>
    <a-modal
      :title="$t('Download-operate-log')"
      :visible="visible"
      width='40%'
      @cancel="handleCancel"
      :maskClosable='false'
      v-dragModal
    >
     <!-- @ok="handleOk" -->
    <!-- :cancelText="$t('Cancel')" :okText="$t('Sure')"  -->
      <a-form :form='form'>
        <a-form-item :label="$t('Time-frame')" v-bind='formlayout' has-feedback>
          <a-range-picker
            v-decorator="['time',{
                  rules:[{required:true,message:$t('Choose')+$t('Time-frame')},]
            }]"
            :show-time="{ format: 'YYYY-MM-DD HH:mm' }"
            format="YYYY-MM-DD HH:mm"
            :placeholder="[$t('Start-time'), $t('End-time')]"
            style="width:100%"
            :locale="rangePickerLocal"
            @change="onChange"
          />
        <!-- @ok="onOk" -->
        </a-form-item>
      </a-form>
      <template slot="footer">
        <a-button key="back" @click="handleCancel">
          {{$t('Cancel')}}
        </a-button>
        <a-button key="submit" type="primary" @click="handleOk" :loading="isLoadingSubmit">
          {{$t('Sure')}}
        </a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import request from '@/request/request'

export default {
  name: "DownloadLog",
  props: ['visible'],
  data() {
    return {
      form:this.$form.createForm(this),
      formlayout:{
        labelCol:{span:6},
        wrapperCol:{span:18}
      },
      rangePickerLocal: {
        "lang": {
          "placeholder": "Select date",
          "rangePlaceholder": ["Start date", "End date"],
          "today": "Today",
          "now": "Now",
          "backToToday": "Back to today",
          "ok": this.$t('Sure'),
          "clear": "Clear",
          "month": "Month",
          "year": "Year",
          "timeSelect": this.$t('Select-time-picker'),
          "dateSelect": this.$t('Select-date-picker'),
          "monthSelect": "Choose a month",
          "yearSelect": "Choose a year",
          "decadeSelect": "Choose a decade",
          "yearFormat": "YYYY",
          "dateFormat": "M/D/YYYY",
          "dayFormat": "D",
          "dateTimeFormat": "M/D/YYYY HH:mm:ss",
          "monthFormat": "MMMM",
          "monthBeforeYear": true,
          "previousMonth": "Previous month (PageUp)",
          "nextMonth": "Next month (PageDown)",
          "previousYear": "Last year (Control + left)",
          "nextYear": "Next year (Control + right)",
          "previousDecade": "Last decade",
          "nextDecade": "Next decade",
          "previousCentury": "Last century",
          "nextCentury": "Next century"
        },
      },
      timeRange: [],
      isLoadingSubmit: false,
    }
  },
  methods: {
    //提交下载操作日志
    handleOk(e) {
      e.preventDefault();
      this.form.validateFields((err,value)=>{
        if(!err){
          this.isLoadingSubmit = true;
          request('post', 'logmanage/pentalog/download',{
            begin_time: this.timeRange[0], //开始时间
            end_time: this.timeRange[1] //结束时间
          },{
            responseType: 'blob'
          }).then(res => {
            // console.log('下载操作日志', res);
            this.handleCancel();
            if(res.status == 200) {
              if(this.$store.state.language == 'zh') {
                this.$message.success('正在下载操作日志');
              }else {
                this.$message.success('Downloading operation log');
              }
              this.downloadBlobCSV(
                res.data,
                '.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel',
                `操作日志(${this.timeRange[0]+'-'+this.timeRange[1]}).csv`
              );
            }else {
              this.$message.error(this.$t('Download-fail'));
            }
          }).catch(err => {
            // console.log(err);
          }).finally(() => {
            this.isLoadingSubmit = false;
          })
        }
      })
    },

    onChange(date, dateString) {
      if(date.length != 0) {
        //moment对象转为时间戳
        // this.timeRange[0] = String(date[0].valueOf()).substring(0,10);
        // this.timeRange[1] = String(date[1].valueOf()).substring(0,10);
        this.timeRange[0] = dateString[0];
        this.timeRange[1] = dateString[1];
      }else {
        this.timeRange = [];
      }
    },

    //关闭下载弹窗
    handleCancel() {
      this.$emit('closeDialog');
    },

    //二进制流下载csv文件
    downloadBlobCSV(data, type, filename) {
      let blob = new Blob([data], {
        type
        // type: '.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
      });
      const url = window.URL.createObjectURL(blob);
      // let filename = '文件流下载' + '.csv';
      const link = document.createElement('a');
      link.style.display = 'none';
      link.href = url;
      link.setAttribute('download', filename);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      this.$message.success(this.$t('Download-success'));
    }
  },
}
</script>